/*
 * @Author: 徐凯 xukai@sinoroad.com
 * @Date: 2023-04-04 22:24:44
 * @Description: utils
 */
import * as echarts from 'echarts'
import { hexaColorToRgba } from '@/utils/index.js'

/**
 * 初始化echarts
 * @param {*} id
 * @param {*} cb
 * @returns
 */
export const initEcharts = (id, cb) => {
  const el = document.getElementById(id)
  if (!el) return
  var myChart = echarts.init(el)
  if (myChart) {
    cb(myChart)
    window.addEventListener('resize', () => {
      myChart.resize()
    })
  }
}

/**
 * 图表高亮动画
 * @param {*} myChart echarts实例
 * @param {*} len 数据长度
 * @param {*} time 移动时间间隔
 * @returns
 */
export const echartsHighlightAnimation = (myChart, len, time = 2000) => {
  let currentIndex = -1
  return setInterval(() => {
    myChart.dispatchAction({
      type: 'downplay',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
    currentIndex = (currentIndex + 1) % len
    myChart.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
  }, time)
}

/**
 * 生成渐变色
 * @param {*} from
 * @param {*} to
 * @returns
 */
export const genLinearGradientColor = (from, to) => {
  return new echarts.graphic.LinearGradient(0, 0, 0, 0.7, [
    {
      offset: 0,
      color: from
    },
    {
      offset: 1,
      color: to
    }
  ])
}

/**
 * 生成渐变色（从做到右渐变）
 * @param {*} from
 * @param {*} to
 * @returns
 */
export const genColorLeftToRight = (from, to) => {
  return new echarts.graphic.LinearGradient(
    0,
    0,
    1.2,
    0,
    [
      {
        offset: 0,
        color: from
      },
      {
        offset: 1,
        color: to
      }
    ],
    false
  )
}

/**
 * 区域渐变色
 * @param {*} color
 * @returns
 */
export const genAreaColor = color => {
  return new echarts.graphic.LinearGradient(
    0,
    0,
    0,
    1,
    [
      {
        offset: 0,
        color: hexaColorToRgba(color, 0.6) // 上面
      },
      {
        offset: 0.4,
        color: hexaColorToRgba(color, 0.1) // 上面
      }
    ],
    false
  )
}
